package com.mmc.sqlSession.xml;

import com.mmc.container.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlMapperBuilder {

    public static Map<String,MappedStatement> parse(InputStream inputStream) throws ClassNotFoundException, DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> select = rootElement.selectNodes("select");
        Map<String,MappedStatement> resultMap=new HashMap<>();
        for (Element element : select) { //id的值
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType"); //输⼊参数class

            Class paramterTypeClass = getClassType(paramterType);
            //返回结果class
            Class resultTypeClass = getClassType(resultType);
            //statementId
            String key = namespace + "." + id;
            //sql语句
            String textTrim = element.getTextTrim();
            //封装 mappedStatement
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterTypeClass);
            mappedStatement.setResultType(resultTypeClass);
            mappedStatement.setSql(textTrim);
            resultMap.put(key,mappedStatement);
    }
    return resultMap;
}

    private static Class getClassType(String paramterType) throws ClassNotFoundException {
        return paramterType!=null?Class.forName(paramterType):null;
    }
    }
